package com.rsscollector.feedrss.parser;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

import org.apache.log4j.Logger;

public class ParserFactory {
	private static Logger logger = Logger.getLogger(ParserFactory.class.getName());

    private String PLUGIN_FILE_PATH = "/parser.properties";
    private HashMap<String, GenericParser> pluginsMap = new HashMap<String, GenericParser>();

    private static ParserFactory instance = null; 

    public static ParserFactory getInstance() {
    	if (instance == null) {
    		instance = new ParserFactory();
    	}
    	return instance;
    }

    public GenericParser getParser(String key) {
    	return pluginsMap.get(key);
    }
    
    private ParserFactory() {
        if (pluginsMap.isEmpty()) {
            try {
                // Read properties file.
                ClassLoader cl = ParserFactory.class.getClassLoader();
                InputStream is = cl.getResourceAsStream(PLUGIN_FILE_PATH);
                Properties properties = new Properties();
                properties.load(is);
                is.close();
                Enumeration classes = properties.keys();
                String c = null;

                while (classes.hasMoreElements()) {
                    c = (String) classes.nextElement();
                    Class mClass = null;
                    try {
                        mClass = Class.forName(properties.getProperty(c));
                        GenericParser object = (GenericParser) mClass.newInstance();
                        pluginsMap.put(c, object);
                    } catch (Exception e) {
                    	logger.error("Error when initializing ParserFactory", e);
                    }
                }
                Collections.unmodifiableMap(pluginsMap);
            } catch (IOException e) {
            	logger.error("Error when initializing ParserFactory", e);
            }
        }
    }
}
